package gov.kqqzyyy.monkey.orderpad.ui;

import android.annotation.SuppressLint;
import android.app.AlertDialog;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.FrameLayout;
import android.widget.ListView;

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.socks.library.KLog;

import java.util.ArrayList;
import java.util.List;
import java.util.Objects;

import butterknife.BindView;
import butterknife.ButterKnife;
import gov.kqqzyyy.monkey.orderpad.R;
import gov.kqqzyyy.monkey.orderpad.adapter.OrderStoredAdapter;
import gov.kqqzyyy.monkey.orderpad.mytools.DateTimeUtil;
import gov.kqqzyyy.monkey.orderpad.network.RetrofitUtil;
import gov.kqqzyyy.monkey.orderpad.network.base.BaseObserver;
import gov.kqqzyyy.monkey.orderpad.network.bean.BaseResponse;
import gov.kqqzyyy.monkey.orderpad.object.StoredDataJson;
import gov.kqqzyyy.monkey.orderpad.object.post_param.StoredOrder;
import io.reactivex.Observable;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.schedulers.Schedulers;


@SuppressLint("NonConstantResourceId")
public class StoredOrderActivity extends NavigationBaseActivity implements AdapterView.OnItemLongClickListener {


    @BindView(R.id.container)
    FrameLayout container;

    ListView mOrderListView;

    OrderStoredAdapter adapter;

    private final Handler myHandler = new Handler();
    private final Runnable mLoadingRunnable = this::loadView;

    private StoredDataJson storedData;

    private List<StoredOrder> dataList;
    private String dateNow;

    private BaseObserver<String> saveObserver;

    @Override
    @SuppressLint("WrongConstant")
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        ButterKnife.bind(this);
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.menu_storedorder, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        int id = item.getItemId();
        if (id == R.id.menu_upload) {
//            showToast("数据保存中，请稍等 "+new Date());
            uploadStoredOrders();
        }
        return super.onOptionsItemSelected(item);
    }

    private void uploadStoredOrders() {
        Gson gson = new Gson();
        if (storedData != null) {
            String data = storedData.getStoredJson();
            if (!data.equals("")) {
                showProgressDialog("提交订单中");
                List<StoredOrder> storedOrderList = gson.fromJson(data, new TypeToken<List<StoredOrder>>() {
                }.getType());
                Observable<BaseResponse<String>> observable = RetrofitUtil.getInstence().doSaveOrderDish(storedOrderList);
                saveObserver = new BaseObserver<String>() {
                    @Override
                    protected void onSuccees(BaseResponse<String> t) {
                        cancelProgressDialog();
                        showToast("订单提交成功");
                        getMySharedPreferences().edit().putString("storeddata", "").apply();
                        doLoadData();
                    }

                    @Override
                    protected void onFailure(Throwable e, boolean isNetWorkError) {
                        cancelProgressDialog();
                        KLog.d("APE", e.getMessage());
                        showToast("订单提交失败\n" + e.getMessage());
                    }

                    @Override
                    protected void onCodeError(BaseResponse<String> t) {
                        super.onCodeError(t);
                        cancelProgressDialog();
                        KLog.d("APE", t.getMsg());
                        showToast("订单提交失败\n" + t.getMsg() + "\n" + t.getSubmsg());
                    }
                };
                observable
                        .subscribeOn(Schedulers.io())
                        .observeOn(AndroidSchedulers.mainThread())
                        .subscribe(saveObserver);
            }
        }
    }


    @Override
    protected void onStop() {
        super.onStop();
        if (saveObserver != null) {
            saveObserver.doCancelRequest();
        }
    }

    private void loadView() {
        container.removeAllViews();
        LayoutInflater.from(this).inflate(R.layout.activity_stored_order, container);
        setActionBarTitle("保存的订单");
        onBindUI();
        adapter = new OrderStoredAdapter(this);
        mOrderListView.setAdapter(adapter);
        doLoadData();
        mOrderListView.setOnItemLongClickListener(this);
    }

    private void onBindUI() {
        mOrderListView = findViewById(R.id.order_stored_listview);
    }

    @Override
    protected void onResume() {
        super.onResume();
        getWindow().getDecorView().post(() -> myHandler.post(mLoadingRunnable));
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            backToOrderMenu();
        }
        return super.onKeyDown(keyCode, event);
    }

    private void backToOrderMenu() {
        Intent intent = new Intent(getApplicationContext(), OrderMenuActivity.class);
        startActivity(intent);
        overridePendingTransition(R.anim.slide_in_left, R.anim.slide_out_right);
        finish();
    }

    private void doLoadData() {
        String storedDataJson = getMySharedPreferences().getString("storeddata", "");
        if (!Objects.requireNonNull(storedDataJson).equals("")) {
            dateNow = DateTimeUtil.getNewServerDate(getMyApplication().getDeltaTime());
            Gson gson = new Gson();
            storedData = gson.fromJson(storedDataJson, new TypeToken<StoredDataJson>() {
            }.getType());
            if (storedData != null && storedData.getSotredDate().equals(dateNow)) {
                dataList = gson.fromJson(storedData.getStoredJson(), new TypeToken<List<StoredOrder>>() {
                }.getType());
                if (dataList != null && dataList.size() > 0) {
                    adapter.setList(dataList);
                } else {
                    showToast("没有保存的订单信息3!");
                }
            } else {
                showToast("没有保存的订单信息2!");
            }
        } else {
            List<StoredOrder> list = new ArrayList<>();
            adapter.setList(list);
            showToast("没有保存的订单信息1!");
        }
    }

    @Override
    public boolean onItemLongClick(AdapterView<?> parent, View view, int position, long id) {

        final String[] items = new String[]{"删除订单"};
        AlertDialog.Builder mChooseDialogBuilder = new AlertDialog.Builder(StoredOrderActivity.this);
        mChooseDialogBuilder.setTitle("订单操作");
        mChooseDialogBuilder.setItems(items, (dialogInterface, which) -> {
            if (which == 0) {
                dataList.remove(position);
                adapter.setList(dataList);
                Gson gson = new Gson();
                String listJson = gson.toJson(dataList);
//                StoredDataJson storedData = new StoredDataJson();
                storedData.setSotredDate(dateNow);
                storedData.setStoredJson(listJson);
                String resultJson = gson.toJson(storedData);
                getMySharedPreferences().edit().putString("storeddata", resultJson).apply();
            }
        });
        mChooseDialogBuilder.show();
        return false;
    }

}
